package com.sdcqjy.property.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.BaseFragment;
import com.sdcqjy.property.base.SimpleBaseActivity;
import com.sdcqjy.property.home.fragment.MessageFragment;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by 磁磁帅 on 2018/5/13.
 * 功能：
 */

public class MessageActivity extends SimpleBaseActivity implements OnTabSelectListener {
    @BindView(R.id.tabLayout)
    SegmentTabLayout tabLayout;
    private BaseFragment[] fragments;
    private BaseFragment oldFragment;

    public static void open(Context context) {
        Intent intent = new Intent(context, MessageActivity.class);
        context.startActivity(intent);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        ButterKnife.bind(this);

        fragments = new BaseFragment[2];
        fragments[0] = MessageFragment.newInstance(0);
        fragments[1] = MessageFragment.newInstance(1);

        Resources res = getResources();
        tabLayout.setTabData(new String[]{res.getString(R.string.weidu), res.getString(R.string.yidu)});
        tabLayout.setOnTabSelectListener(this);

        switchFragment(fragments[0]);
    }

    public void switchFragment(BaseFragment fragment) {
        if (fragment == oldFragment) return;
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (!fragment.isAdded()) {
            transaction.add(R.id.layoutFrame, fragment, fragment.getClass().getName());
        } else {
            transaction.show(fragment);
            fragment.onResume();
        }
        if (oldFragment != null) {
            transaction.hide(oldFragment);
        }
        oldFragment = fragment;
        transaction.commitAllowingStateLoss();
    }

    public void onTabSelect(int i) {
        switchFragment(fragments[i]);
    }

    public void onTabReselect(int i) {
    }
}
